<template>
  <el-drawer
    :wrapper-closable="false"
    title="分配权限"
    :size="500"
    append-to-body
    :visible.sync="innerValue"
    :close-on-click-modal="false"
    @open="onDrawerOpen"
  >
    <div class="relative flex h-full flex-col px-[16px] pb-[64px] pt-0">
      <div class="common-secondary-bg">
        <div class="common-secondary-title"></div>
        菜单和按钮权限
      </div>
      <div class="flex min-h-0 flex-1 flex-col overflow-y-auto">
        <!-- <div>菜单和按钮权限</div> -->
        <el-tree
          ref="tree"
          :data="roleMs"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          @node-click="handleNodeClick"
        >
        </el-tree>
      </div>
      <footer class="common-drawer-footer">
        <t-button class="common-search-btn" type="primary" @click="onSubmit">提 交</t-button>
        <t-button class="common-search-btn" type="default" plain @click="innerValue = false">取 消</t-button>
      </footer>
    </div>
  </el-drawer>
</template>

<script>
import { convertToTree } from "@/util/index";
import vModelMixin from "@/mixin/v-model";
import { systemRoleAssignPermission, systemRoleDetail } from "@/api/role";
import { systemPermissionSystem } from "@/api/permission";

export default {
  name: "DetailDrawerRole",
  components: {},
  mixins: [vModelMixin],
  props: {
    code: {
      type: [String, Number],
      required: true,
    },
    id: {
      type: [String, Number],
      required: true,
    },
  },
  data() {
    return {
      roleMs: [],
      defaultProps: {
        label: "name",
      },
      roleId: "",
      permissionId: [],
      defaultCheckedKeys: [],
    };
  },
  computed: {},
  methods: {
    handleNodeClick(data) {},
    async onDrawerOpen() {
      systemPermissionSystem().then(async (res) => {
        this.roleMs = convertToTree(res);
        const { permissions } = await systemRoleDetail({ id: this.id });
        permissions
          ?.map((item) => item.id)
          .forEach((i, n) => {
            const node = this.$refs.tree.getNode(i);
            if (node.isLeaf) {
              this.$refs.tree.setChecked(node, true);
            }
          });
      });
    },
    async onSubmit() {
      const permissionId = this?.$refs?.tree?.getCheckedNodes();
      const halfCheckedNodes = this?.$refs?.tree?.getHalfCheckedNodes();
      const needId = [...permissionId, ...halfCheckedNodes].map((item) => item.code);
      const data = await systemRoleAssignPermission({ roleCode: this.code, permissionCode: needId });
      this.$emit("closeDrawer");
    },

    onDrawerClosed() {},
  },
};
</script>

<style lang="scss" scoped></style>
